import axios, {
  AxiosError,
  AxiosInstance,
  AxiosResponse,
  InternalAxiosRequestConfig
} from 'axios'
import qs from 'qs'
import { useCache } from '@/hooks/basic/useCache'
import { getAccessToken, getRefreshToken, removeToken, setToken } from '@/utils/business/auth'
import { mockData } from '@/api/mock'
import { basicConfig, errorCodeDic, whiteList, ignoreMsgs } from './constants'

const message = useMessage()

export const isRelogin = { show: false } // 是否显示重新登录
const refreshToken = async () => {
  return await axios.post(basicConfig.base_url + '/system/auth/refresh-token?refreshToken=' + getRefreshToken())
}
const handleAuthorized = () => {
  const { t } = useI18n()
  if (!isRelogin.show) {
    // 如果已经到重新登录页面则不进行弹窗提示
    if (window.location.href.includes('login?redirect=')) {
      return
    }
    isRelogin.show = true
    message.confirm(t('sys.api.timeoutMessage'), t('common.tips.confirmTitle'), {
      showCancelButton: false,
      closeOnClickModal: false,
      showClose: false,
      confirmButtonText: t('login.relogin'),
      type: 'warning'
    }).then(() => {
      const { wsCache } = useCache()
      // resetRouter() // 重置静态路由表
      wsCache.clear()
      removeToken()
      isRelogin.show = false
      // 干掉token后再走一次路由让它过router.beforeEach的校验
      window.location.href = window.location.href
    }).catch(() => {})
  }
  return Promise.reject(t('sys.api.timeoutMessage'))
}

// 创建axios实例
const service: AxiosInstance = axios.create({
  baseURL: basicConfig.base_url, // api 的 base_url
  timeout: basicConfig.request_timeout, // 请求超时时间
  withCredentials: false // 禁用 Cookie 等信息
})

// request 拦截器
service.interceptors.request.use(
  (config: InternalAxiosRequestConfig) => {
    // 是否需要设置 token
    let isToken = true
    whiteList.some((v) => {
      if (config.url) {
        config.url.indexOf(v) > -1
        return (isToken = false)
      }
    })
    if (getAccessToken() && !isToken) {
      config.headers.Authorization = 'Bearer ' + getAccessToken() // 让每个请求携带自定义token
    }

    // post 参数处理
    if (
      config.method?.toUpperCase() === 'POST' &&
      config.headers['Content-Type'] === 'application/x-www-form-urlencoded'
    ) {
      config.data = qs.stringify(config.data || false)
    }

    // get 参数处理
    const params = config.params || {}
    if (config.method?.toUpperCase() === 'GET' && params) {
      let url = config.url + '?'
      for (const propName of Object.keys(params)) {
        const value = params[propName]
        if (value !== void 0 && value !== null && typeof value !== 'undefined') {
          if (typeof value === 'object') {
            for (const val of Object.keys(value)) {
              const params = propName + '[' + val + ']'
              const subPart = encodeURIComponent(params) + '='
              url += subPart + encodeURIComponent(value[val]) + '&'
            }
          } else {
            url += `${propName}=${encodeURIComponent(value)}&`
          }
        }
      }
      // 给 get 请求加上时间戳参数，避免从缓存中拿数据
      // const now = new Date().getTime()
      // params = params.substring(0, url.length - 1) + `?_t=${now}`
      url = url.slice(0, -1)
      config.params = {}
      config.url = url
    }

    return config
  },
  (error: AxiosError) => {
    Promise.reject(error)
  }
)

// response 拦截器
let requestList: any[] = [] // 请求队列
let isRefreshToken = false // 是否正在刷新中
service.interceptors.response.use(
  async (response: AxiosResponse<any>) => {
    const { data, config, request } = response

    // 返回[HTTP]请求没有返回值
    if (!data) {
      throw new Error()
    }

    // 二进制数据则直接返回
    if (['blob', 'arraybuffer'].includes(request.responseType)) {
      return response.data
    }
    
    const { t } = useI18n()

    // 未设置状态码则默认成功状态
    const code = data.code || basicConfig.result_code
    // 获取错误信息
    const msg = data.msg || errorCodeDic[code] || errorCodeDic['default']
    if (ignoreMsgs.indexOf(msg) !== -1) {
      // 如果是忽略的错误码，直接返回 msg 异常
      return Promise.reject(msg)
    } else if (code === 401) {
      // 如果未认证，并且未进行刷新令牌，说明可能是访问令牌过期了
      if (!isRefreshToken) {
        isRefreshToken = true
        // 1. 如果获取不到刷新令牌，则只能执行登出操作
        if (!getRefreshToken()) {
          return handleAuthorized()
        }
        // 2. 进行刷新访问令牌
        try {
          const refreshTokenRes = await refreshToken()
          // 2.1 刷新成功，则回放队列的请求 + 当前请求
          setToken(refreshTokenRes.data.data)
          config.headers!.Authorization = 'Bearer ' + getAccessToken()
          requestList.forEach((cb: any) => {
            cb()
          })
          requestList = []
          return service(config)
        } catch (e) {
          // 为什么需要 catch 异常呢？刷新失败时，请求因为 Promise.reject 触发异常。
          // 2.2 刷新失败，只回放队列的请求
          requestList.forEach((cb: any) => {
            cb()
          })
          // 提示是否要登出。即不回放当前请求！不然会形成递归
          return handleAuthorized()
        } finally {
          requestList = []
          isRefreshToken = false
        }
      } else {
        // 添加到队列，等待刷新获取到新的令牌
        return new Promise((resolve) => {
          requestList.push(() => {
            config.headers!.Authorization = 'Bearer ' + getAccessToken() // 让每个请求携带自定义token 请根据实际情况自行修改
            resolve(service(config))
          })
        })
      }
    } else if (code === 500) {
      message.notifyError(t('sys.api.errMsg500'))
      return Promise.reject(new Error(msg))
    } else if (code !== 200) {
      if (msg === '无效的刷新令牌') {
        // hard coding：忽略这个提示，直接登出
        console.log(msg)
      } else {
        message.notifyError(msg)
      }
      return Promise.reject('error')
    } else {
      return data
    }
  },
  (error: AxiosError) => {
    // @临时处理
    return Promise.resolve({ data: mockData[error.config.url] || {} })
    const { t } = useI18n()
    let msg = error.message
    if (msg === 'Network Error') {
      msg = t('sys.api.errorMessage')
    } else if (msg.includes('timeout')) {
      msg = t('sys.api.apiTimeoutMessage')
    } else if (msg.includes('Request failed with status code')) {
      msg = t('sys.api.apiRequestFailed') + msg.substr(msg.length - 3)
    }
    message.notifyError(msg)
    return Promise.reject(error)
  }
)

export {
  service
}
